<?php
namespace Service;

use Hoa\Registry\Registry;
use Library\Redis;
use Library\Log;
use Logic\ProdLogic;
use Model\Prod;


/**
 * OrderService
 * @author los_gsy
 */
class OrderService extends BaseService {
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
	}


	/**
	 * test
	 */
	static public function test() {
		return __METHOD__;
	}


	/**
	 * 下单
	 * @param int $prodId
	 * @param int $prodQty
	 * @return array
	 */
	static public function placeOrder($prodId, $prodQty) {
		//定义变量
		$conf = Registry::get('conf');
		$ret = $conf['status'][200];

		//验证库存数量
		$prodCnt = ProdLogic::getProdCnt($prodId);
		if ($prodCnt <= 0) {
			$ret = $conf['status'][40020101];
			return $ret;
		}

		//原子减库存
		$redis_key = 'prod:cnt:' . $prodId;
		//Redis::multi();
		$newProdCnt = Redis::decrby($redis_key, $prodQty);
		Log::debug(__METHOD__ . ': $newProdCnt = ' . var_export($newProdCnt, true));
		if ($newProdCnt < 0) {
			//Redis::discard();
			Redis::incrby($redis_key, $prodQty);
			$ret = $conf['status'][40020101];
			return $ret;
		}
		//Redis::exec();

		//更新DB库存
		//TODO: 这一步可以改为异步执行
		$data = [];
		$data['cnt'] = $newProdCnt;
		Prod::saveProd($data, $prodId);
		return $ret;
	}





}